package com.group.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.group.dao.GeneralBeanDao;
import com.group.dao.NewsDao;
import com.group.model.News;
import com.group.model.Ticker;
import com.group.model.TickerCurrency;
import com.group.util.WeiXinConf;
import com.group.util.WeiXinUtils;

@Service
public class ScheduleService {
	private static final Logger logger = LoggerFactory.getLogger(ScheduleService.class);

	@Autowired
	GeneralBeanDao beanDao;

	@Autowired
	NewsDao newsDao;

	Random r = new Random();

	/**
	 * 自动增加新闻阅读
	 */
	@Scheduled(initialDelay = WeiXinConf.delay, fixedRate = 1000 * 60)
	public void increaseRead() {
		// 100%的文章发布之后3小时之内，每分钟1次点击，每次点击随机加1-20
		List<News> nlist = newsDao.querySpecialNews0();
		for (News n : nlist) {
			int read = r.nextInt(20) + 1;
			logger.info("第0类自动增加新闻 id = " + n.getId() + " 的阅读次数 " + read + " 次");
			n.setRead(n.getRead() + read);
			beanDao.save(n);
		}

		// 20%的文章，3小时之内，每分钟2次点击，每次点击随机加1-20
		nlist = newsDao.querySpecialNews1();
		for (News n : nlist) {
			int read = r.nextInt(40) + 1;
			logger.info("第1类自动增加新闻 id = " + n.getId() + " 的阅读次数 " + read + " 次");
			n.setRead(n.getRead() + read);
			beanDao.save(n);
		}

		// 20%的文章，3小时之内，每分钟3次点击，每次点击随机加1-20，发布之后3-6小时，每分钟1次点击，每次1-20
		nlist = newsDao.querySpecialNews2();
		for (News n : nlist) {
			int read = r.nextInt(60) + 1;
			logger.info("第2类自动增加新闻 id = " + n.getId() + " 的阅读次数 " + read + " 次");
			n.setRead(n.getRead() + read);
			beanDao.save(n);
		}

		nlist = newsDao.querySpecialNews21();
		for (News n : nlist) {
			int read = r.nextInt(20) + 1;
			logger.info("第2类自动增加新闻 id = " + n.getId() + " 的阅读次数 " + read + " 次");
			n.setRead(n.getRead() + read);
			beanDao.save(n);
		}

	}

	/**
	 * 更新币的信息
	 */
	// @Scheduled(initialDelay = WeiXinConf.delay, fixedRate = 1000 * 500)
	public void updateTicker() {
		String result = WeiXinUtils.get("https://api.coinmarketcap.com/v1/ticker/?convert=CNY&limit=150");

		JSONArray jlist = JSONObject.parseArray(result);

		for (int i = 0; i < jlist.size(); i++) {
			JSONObject jo = jlist.getJSONObject(i);
			String cid = jo.getString("id");
			if (StringUtils.isEmpty(cid)) {
				logger.info("查询币的接口返回结果: " + result);
				return;
			}

			Ticker ticker = new Ticker();
			ticker.setCid(cid);
			Ticker exist = beanDao.queryOne(ticker);
			if (exist != null) {
				ticker.setId(exist.getId());
			}

			ticker.setAvailableSupply(jo.getString("available_supply"));
			ticker.setChange24h(jo.getString("percent_change_24h"));
			ticker.setMarketCapCny(jo.getString("market_cap_cny"));
			ticker.setMarketCapUsd(jo.getString("market_cap_usd"));
			ticker.setMaxSupply(jo.getString("max_supply"));
			ticker.setName(jo.getString("name"));
			ticker.setPriceBtc(jo.getString("price_btc"));
			ticker.setPriceCny(jo.getString("price_cny"));
			ticker.setPriceUsd(jo.getString("price_usd"));
			ticker.setSymbol(jo.getString("symbol"));
			ticker.setVolumeCny24h(jo.getString("24h_volume_cny"));
			ticker.setVolumeUsd24h(jo.getString("24h_volume_usd"));
			ticker.setRank(jo.getInteger("rank"));
			beanDao.save(ticker);

		}

	}

	/**
	 * 更新czr币的图
	 * 
	 * @throws Exception
	 */
	// @Scheduled(initialDelay = WeiXinConf.delay, fixedRate = 1000 * 60)
	public void updateCzr() throws Exception {
		String result = WeiXinUtils.formPost("http://www.bcex.ca/market/nkline", "needTickers=1&symbol=czr2eth&type=1day&size=1000");

		if (result.contains("datas")) {
			logger.info("czr : " + result);
			TickerCurrency tc = beanDao.quickQueryOne(TickerCurrency.class, "cid", "czr");
			// 获取成功,缓存
			JSONObject obj = JSONObject.parseObject(result);
			JSONArray jarray = obj.getJSONObject("datas").getJSONArray("data");
			Ticker tk = beanDao.quickQueryOne(Ticker.class, "cid", "ethereum");
			List<List<BigDecimal>> content = new ArrayList<>();
			for (int i = 0; i < jarray.size(); i++) {
				JSONArray data = jarray.getJSONArray(i);

				List<BigDecimal> a = new ArrayList<>();
				a.add(data.getBigDecimal(0));
				a.add(data.getBigDecimal(4).multiply(new BigDecimal(Double.parseDouble(tk.getPriceCny()))).setScale(8, BigDecimal.ROUND_HALF_UP));

				content.add(a);
			}
			JSONObject out = new JSONObject();
			out.put("market_cap_by_available_supply", content);

			tc.setContent(out.toJSONString());
			beanDao.save(tc);
			logger.info("---更新crz币图成功--");
		}

	}

}
